package com.study.fetch;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader.Feature;
import com.alibaba.fastjson2.TypeReference;
import com.study.fetch.ClsFetch.ClsDTO.DayEventDTO;
import com.study.fetch.ClsFetch.ClsDTO.Resp;
import com.study.fetch.ClsFetch.ClsDTO.TzCalendar.DayEvent;
import com.study.fetch.ClsFetch.ClsDTO.TzCalendar.MonthEvent;
import com.study.fetch.ClsFetch.ClsDTO.TzCalendar.MonthEventDTO;
import lombok.Data;
import lombok.experimental.Accessors;
import org.assertj.core.util.Lists;
import org.junit.jupiter.api.Test;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

/**
 * @author zhuzi
 * 2024/3/31 22:57
 * 财联社,投资日历
 */
public class ClsFetch {

    static RestTemplate restTemplate;

    static {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setReadTimeout(6 * 1000);
        factory.setConnectTimeout(10000);
        restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(factory));
    }

    @Test
    public void fetch() {
        //需要传入月初和月末
        String url = "https://x-data.cls.cn/api/calendar/tops?ov=15.7&platform=ipad&province_code=1101&selected=m&sv=8.3.4&start_day={}&end_day={}";

        LocalDate startLocal = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
        LocalDate endLocal = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());

        HttpResponse response = HttpRequest.get(StrUtil.format(url, startLocal.toString(), endLocal.toString())).timeout(5000).execute();

        String body = response.body();
        System.out.println(body);

        Resp<MonthEvent> monthEventResp = JSON.parseObject(body, new TypeReference<Resp<MonthEvent>>() {
        }, Feature.SupportAutoType, Feature.SupportSmartMatch);

        System.out.println(monthEventResp);

        MonthEventDTO build = MonthEventDTO.build(monthEventResp.getData().get(0));
        System.out.println(build.ding());
    }

    @Test
    public void fetchDayRest() {

    }

    @Test
    public void fetchDay() {
        //需要传入月初和月末
        String url = "https://x-data.cls.cn/api/calendar/events?start_day={}&end_day={}";

        LocalDate startLocal = LocalDate.now().plusDays(1);
        LocalDate endLocal = LocalDate.now().plusDays(2);

        HttpResponse response = HttpRequest.get(StrUtil.format(url, startLocal.toString(), endLocal.toString())).timeout(5000).execute();

        String body = response.body();
        System.out.println(body);

        Resp<DayEvent> dayEventResp = JSON.parseObject(body, new TypeReference<Resp<DayEvent>>() {
        }, Feature.SupportAutoType, Feature.SupportSmartMatch);

        System.out.println(dayEventResp);

        List<DayEvent> data = dayEventResp.getData();
        List<DayEventDTO> dayEventDTOList = DayEventDTO.build(data);
        for (DayEventDTO dto : dayEventDTOList) {
            System.out.println(dto);
        }

    }

    interface ClsDTO {
        /**
         * 投资日历
         */
        interface TzCalendar {

            @Data
            @Accessors(chain = true)
            class MonthEventDTO {
                private String id;

                private String title;
                private List<String> articles;
                private List<String> interpretImg;

                public static MonthEventDTO build(MonthEvent event) {
                    if (Objects.isNull(event)) {
                        return null;
                    }
                    return new MonthEventDTO().setId(event.getId()).setTitle(event.getTop().getTitle()).setInterpretImg(event.getTop().getInterpretImg());
                }

                public String ding() {
                    ArrayList<String> list = Lists.newArrayList("🎉 财联社消息——投资日历(月)\n");
                    list.add("🏆 " + title);
                    list.add("📌 " + String.join(",", interpretImg));
                    return String.join("\n", list);
                }

            }

            @Data
            @Accessors(chain = true)
            class MonthEvent {
                private String id;
                private String type;
                private Top top;

                @Data
                @Accessors(chain = true)
                public static class Top {
                    private String title;
                    private List<String> articles;
                    private List<String> interpretImg;
                }
            }

            @Data
            @Accessors
            class DayEvent {
                private String calendarDay;
                private List<DayItem> items;
            }
        }

        @Data
        @Accessors(chain = true)
        class DayItem {
            private String value;
            private List<ItemDetail> items;
        }

        @Data
        @Accessors(chain = true)
        class DayEventDTO {
            private String value;
            private String id;
            private String calendarTime;
            private String type;

            private String title;
            private int star;
            private String stars;

            public static List<DayEventDTO> build(List<DayEvent> dayEvents) {
                ArrayList<DayEventDTO> list = Lists.newArrayList();

                for (DayEvent dayEvent : dayEvents) {
                    String calendarDay = dayEvent.getCalendarDay();
                    for (DayItem item : dayEvent.getItems()) {
                        String country = item.getValue();
                        for (ItemDetail itemDetail : item.getItems()) {
                            DayEventDTO dayEventDTO = new DayEventDTO().setValue(country).setCalendarTime(calendarDay)//
                                    .setId(itemDetail.getId()).setType(itemDetail.getType())//
                                    .setTitle(itemDetail.getEvent().getTitle())//
                                    .setStar(itemDetail.getEvent().getStar())//
                                    .setStars(itemDetail.getEvent().getStars());
                            list.add(dayEventDTO);
                        }
                    }
                }
                list.sort(Comparator.comparing(DayEventDTO::getValue).thenComparing(DayEventDTO::getStars));
                return list;
            }
        }

        @Data
        @Accessors(chain = true)
        class ItemDetail {
            private String id;
            private String calendarTime;
            private String type;
            private Events event;


        }

        @Data
        @Accessors(chain = true)
        class Events {
            private String title;
            private int star;
            private String stars;

            public void setStar(int star) {
                this.star = star;
                this.stars = StrUtil.repeat("🌟", star);
            }
        }

        @Data
        @Accessors(chain = true)
        class Resp<T> {
            private String code;
            private List<T> data;
        }

    }


}

